/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BookRequestDialog.java
 *
 * Created on Apr 22, 2011, 2:05:08 AM
 */
package org.libarae.client;

import java.net.SocketTimeoutException;

import javax.swing.JOptionPane;

import org.libarae.communication.ClientInterface;
import org.libarae.communication.common.Book;
import org.libarae.communication.common.Message;
import org.libarae.communication.common.MessageThread;
import org.libarae.communication.request.SendMessageRequest;
import org.libarae.communication.response.Response;

/**
 *
 * @author Ben
 */
@SuppressWarnings("serial")
public class BookRequestDialog extends javax.swing.JFrame {

    private Book mBook;
    private MainScreen mMainScreen;

    /** Creates new form BookRequestDialog */
    public BookRequestDialog(Book mBook, MainScreen mMainScreen) {
        this.mBook = mBook;
        this.mMainScreen = mMainScreen;

        initComponents();

        lblBook.setText(mBook.getTitle());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblRequestingBook = new javax.swing.JLabel();
        lblBook = new javax.swing.JLabel();
        scrPersonalMessage = new javax.swing.JScrollPane();
        txtPersonalMessage = new javax.swing.JTextArea();
        lblNote = new javax.swing.JLabel();
        btnSubmit = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setLocationByPlatform(true);

        lblRequestingBook.setText("Requesting book:");

        lblBook.setText(" ");

        txtPersonalMessage.setColumns(20);
        txtPersonalMessage.setLineWrap(true);
        txtPersonalMessage.setRows(5);
        scrPersonalMessage.setViewportView(txtPersonalMessage);

        lblNote.setText("If you would like to add a personal message, please add it below.");

        btnSubmit.setText("Submit");
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblRequestingBook)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblBook))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(lblNote))
                            .addComponent(scrPersonalMessage, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnSubmit)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancel)
                        .addGap(24, 24, 24))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblRequestingBook)
                    .addComponent(lblBook))
                .addGap(18, 18, 18)
                .addComponent(lblNote)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrPersonalMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCancel)
                    .addComponent(btnSubmit))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
        MessageThread mt = new MessageThread();

        mt.setUser2(mBook.getOwnerID());
        mt.setBid(mBook.getBID());
        mt.setSubject("Book Request: " + mBook.getTitle());

        Message m = new Message();
        m.setToUser(mBook.getOwnerID());

        String message = txtPersonalMessage.getText();

        message = message.replaceAll("\n", "<br>");

        m.setMessageText("I would like to borrow the following book from your personal library: " + mBook.getTitle() + "<br><br>" + message);

        SendMessageRequest r = new SendMessageRequest();

        r.setAction(SendMessageRequest.BOOK_REQUEST);
        r.setMessage(m);
        r.setMessageThread(mt);

        Response response = null;

        try {
            response = ClientInterface.sendRequest(r);
        }
        catch(SocketTimeoutException e)
        {
            JOptionPane.showMessageDialog(null, "Request timed out. Please try again.");
            return;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        if (response == null) {
            System.err.println("Server could not be contacted.");
        }

        if (response.getStatus() == Response.STATUS_GOOD) {
            mMainScreen.getBookInfoPanel().refreshBook();

            this.dispose();
        }

        // Handle failure
    }//GEN-LAST:event_btnSubmitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new BookRequestDialog(new Book(), new MainScreen()).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSubmit;
    private javax.swing.JLabel lblBook;
    private javax.swing.JLabel lblNote;
    private javax.swing.JLabel lblRequestingBook;
    private javax.swing.JScrollPane scrPersonalMessage;
    private javax.swing.JTextArea txtPersonalMessage;
    // End of variables declaration//GEN-END:variables
}
